package com.moorror.cola.strategy.plugin.view.component;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.util.NlsActions;
import org.jetbrains.annotations.NotNull;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author jiyanghuang
 * @Date 2022/3/16 10:51 PM
 */
public class CSMultiSelect extends DefaultActionGroup{

    private Set<String> itemSelects = new HashSet<>();

    public CSMultiSelect(Set<String> allItems, String shortName){
        super(shortName, true);
        getTemplatePresentation().setIcon(AllIcons.General.Settings);
        getTemplatePresentation().setText(shortName);
        getTemplatePresentation().setDescription(shortName);
        for(String item : allItems){
            add(new SelectToggleAction(item, item));
        }
    }

    public void update(Set<String> allItems){
        removeAll();
        for(String item : allItems){
            if("None".equals(item)){
                continue;
            }
            add(new SelectToggleAction(item, item));
        }
    }

    public Set<String> itemSelects(){
        return itemSelects;
    }

    private class SelectToggleAction extends ToggleAction {

        private String itemName;

        public SelectToggleAction(String itemName, @NlsActions.ActionText String message){
            super(message);
            this.itemName = itemName;
        }
        @Override
        public boolean isSelected(@NotNull AnActionEvent e) {
            return itemSelects.contains(itemName);
        }

        @Override
        public void setSelected(@NotNull AnActionEvent e, boolean state) {
            if (state) {
                itemSelects.add(itemName);
            }
            else {
                itemSelects.remove(itemName);
            }
        }
    }
}
